// wx-diagnose.js - 完整的诊断工具
class WxWorkDiagnose {
	constructor() {
		this.diagnoseResults = [];
	}

	async fullDiagnose() {
		console.log('🚀 开始企业微信SDK完整诊断...');

		// 1. 环境检测
		await this.checkEnvironment();

		// 2. SDK加载检测
		await this.checkSDKLoading();

		// 3. 方法存在性检测
		await this.checkMethods();

		// 4. 配置参数检测
		await this.checkConfigParams();

		// 5. 输出诊断报告
		this.outputReport();

		return this.diagnoseResults;
	}

	async checkEnvironment() {
		console.log('📱 检查运行环境...');

		const ua = navigator.userAgent.toLowerCase();
		const isWxWork = ua.includes('wxwork');
		const isWeChat = ua.includes('micromessenger');

		this.diagnoseResults.push({
			step: '环境检测',
			result: isWxWork ? '✅ 在企业微信中' : '❌ 不在企业微信中',
			details: `UserAgent: ${navigator.userAgent}`
		});

		if (!isWxWork) {
			this.diagnoseResults.push({
				step: '环境警告',
				result: '❌ 请在企业微信中打开此页面',
				details: '普通微信或浏览器不支持agentConfig'
			});
		}

		return isWxWork;
	}

	async checkSDKLoading() {
		console.log('📦 检查SDK加载...');

		// 清理可能存在的旧SDK
		this.cleanExistingSDK();

		// 尝试多种SDK加载方式
		const sdkUrls = [
			'https://open.work.weixin.qq.com/wwopen/js/jwxwork-1.0.0.js',
			'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
			'https://open.work.weixin.qq.com/wwopen/js/jwxwork.js'
		];

		for (let url of sdkUrls) {
			const success = await this.tryLoadSDK(url);
			if (success) {
				this.diagnoseResults.push({
					step: 'SDK加载',
					result: `✅ SDK加载成功: ${url}`,
					details: `使用的SDK地址: ${url}`
				});
				return true;
			}
		}

		this.diagnoseResults.push({
			step: 'SDK加载',
			result: '❌ 所有SDK加载尝试都失败',
			details: '请检查网络或CDN可用性'
		});

		return false;
	}

	cleanExistingSDK() {
		const scripts = document.querySelectorAll('script[src*="wx"], script[src*="weixin"], script[src*="work"]');
		scripts.forEach(script => script.remove());
		delete window.wx;
		delete window.WeixinJSBridge;
	}

	async tryLoadSDK(url) {
		return new Promise((resolve) => {
			const script = document.createElement('script');
			script.src = url;
			script.onload = () => {
				setTimeout(() => {
					resolve(typeof wx !== 'undefined');
				}, 300);
			};
			script.onerror = () => resolve(false);
			document.head.appendChild(script);
		});
	}

	async checkMethods() {
		console.log('🔧 检查方法存在性...');

		if (typeof wx === 'undefined') {
			this.diagnoseResults.push({
				step: '方法检测',
				result: '❌ wx对象未定义',
				details: 'SDK可能没有正确加载'
			});
			return false;
		}

		const requiredMethods = ['config', 'ready', 'error', 'agentConfig'];
		const availableMethods = Object.keys(wx).filter(key => typeof wx[key] === 'function');

		this.diagnoseResults.push({
			step: 'wx对象方法',
			result: `找到 ${availableMethods.length} 个方法`,
			details: `可用方法: ${availableMethods.join(', ')}`
		});

		requiredMethods.forEach(method => {
			const exists = typeof wx[method] === 'function';
			this.diagnoseResults.push({
				step: `方法 ${method}`,
				result: exists ? '✅ 存在' : '❌ 不存在',
				details: exists ? '方法可用' : '方法缺失，可能使用了错误的SDK'
			});
		});

		return requiredMethods.every(method => typeof wx[method] === 'function');
	}

	async checkConfigParams() {
		console.log('⚙️ 检查配置参数...');

		// 这里可以添加对配置参数的检查
		this.diagnoseResults.push({
			step: '配置参数',
			result: '⚠️ 需要后端接口验证',
			details: '请确保corpId、agentId、签名等参数正确'
		});

		return true;
	}

	outputReport() {
		console.log('📊 === 诊断报告 ===');
		this.diagnoseResults.forEach(item => {
			console.log(`${item.step}: ${item.result}`);
			if (item.details) {
				console.log(`   详情: ${item.details}`);
			}
		});

		// 在页面上显示诊断结果
		this.showInPage();
	}

	showInPage() {
		const div = document.createElement('div');
		div.style.cssText = `
      position: fixed;
      top: 10px;
      right: 10px;
      background: white;
      border: 2px solid #007acc;
      padding: 15px;
      max-width: 500px;
      max-height: 400px;
      overflow-y: auto;
      z-index: 10000;
      font-family: monospace;
      font-size: 12px;
      box-shadow: 0 0 10px rgba(0,0,0,0.3);
    `;

		let html = '<h3>🚀 企业微信SDK诊断报告</h3>';
		this.diagnoseResults.forEach(item => {
			const color = item.result.includes('✅') ? 'green' :
				item.result.includes('❌') ? 'red' : 'orange';
			html += `
        <div style="margin: 5px 0; border-bottom: 1px solid #eee;">
          <strong style="color: ${color}">${item.result}</strong><br/>
          <span style="color: #666;">${item.step}</span><br/>
          <small style="color: #999;">${item.details}</small>
        </div>
      `;
		});

		// div.innerHTML = html;
		// document.body.appendChild(div);
	}
}

// 使用诊断工具
const diagnose = new WxWorkDiagnose();
diagnose.fullDiagnose();